﻿@using System.Net.Http.Headers
@using System.Text
@using System.Text.Json
@using System.Globalization
@using Tool.Components.Pages.Common
@using Tool.Models
@using Tool.Services
@inject IHttpClientFactory httpClientFactory
@inject IDialogService dialogService
@inject EncryptHelper encryptHelper
@inject CustomerService customerService
@inject ISnackbar Snackbar
@inject LoginService loginService
<MudGrid>
    <MudItem xs="3">
        <MudTextField @bind-Value="_userCode" Label="单位编码/名称" Variant="Variant.Text" Adornment="Adornment.Start"
                      AdornmentIcon="@Icons.Material.Filled.LockPerson" Clearable="true" />
    </MudItem>
    <MudItem xs="3">
        <MudTextField @bind-Value="_tableCount" Label="分表数量" Variant="Variant.Text" Adornment="Adornment.Start"
                      AdornmentIcon="@Icons.Material.Filled.Numbers" Clearable="true" />
    </MudItem>
    <MudItem xs="3">
        <TableSplitIndex TableCount="@_tableCount" UserCode="@_userCodeStr"></TableSplitIndex>
    </MudItem>

    <MudItem xs="3" Class="align-content-center">
        <MudButton Class="align-self-center" FullWidth="true" Disabled="@_processing" OnClick="SearchCustomers" Variant="Variant.Filled" Color="Color.Primary">
            @if (_processing)
            {
                <MudProgressCircular Class="ms-n1" Indeterminate="true" />
                <MudText Class="ms-2">Processing</MudText>
            }
            else
            {
                <MudText>@ButtonText</MudText>
            }
        </MudButton>
    </MudItem>
    <MudItem xs="12">
        <MudTable Items="@_customers" Dense="true" Hover="true" Bordered="true" Striped="true">
            <ToolBarContent>
                <MudText Typo="Typo.h6">单位信息</MudText>
                <MudSpacer />
                <MudTextField @bind-Value="_searchString" Placeholder="Search" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.Search" IconSize="Size.Medium" Class="mt-0"></MudTextField>
            </ToolBarContent>
            <HeaderContent>
                <MudTh>Id</MudTh>
                <MudTh>UserCode</MudTh>
                <MudTh>CustomerName</MudTh>
                <MudTh>CompanyCode</MudTh>
                <MudTh>AdmdivCode</MudTh>
                <MudTh>AdmdivName</MudTh>
                <MudTh>FinAdmdivCode</MudTh>
                <MudTh>GroupName</MudTh>
                <MudTh>Status</MudTh>
            </HeaderContent>
            <RowTemplate>
                <MudTd DataLabel="Nr">@context.Id</MudTd>
                <MudTd DataLabel="Sign">@context.UserCode</MudTd>
                <MudTd DataLabel="Name">@context.CustomerName</MudTd>
                <MudTd DataLabel="Position">@context.CompanyCode</MudTd>
                <MudTd DataLabel="AdmdivCode">@context.AdmdivCode</MudTd>
                <MudTd DataLabel="AdmdivName">@context.AdmdivName</MudTd>
                <MudTd DataLabel="FinAdmdivCode">@context.FinAdmdivCode</MudTd>
                <MudTd DataLabel="GroupName">@context.GroupName</MudTd>
                <MudTd DataLabel="GroupName">@context.Status</MudTd>
            </RowTemplate>
            <PagerContent>
                <MudTablePager />
            </PagerContent>
        </MudTable>
    </MudItem>
</MudGrid>

@code {
    private string _userCode = "";
    private string _userCodeStr = "";
    private int _tableCount = 128;

    [Parameter]
    public string ButtonText { get; set; } = "获取单位信息";

    private bool _processing = false;

    [Parameter]
    public string SelectedSite { get; set; }
    [Parameter]
    public HttpResponseHeaders ResponseHeaders { get; set; }

    [Parameter]
    public EventCallback<CustomerDto> OnGetCustomer { get; set; }

    private List<CustomerDto> _customers { get; set; } = new List<CustomerDto>();
    private string _searchString = string.Empty;

    private async Task SearchCustomers()
    {
        _processing = true;
        try
        {

            var sql = string.Empty;
            if (_userCode.StartsWith("YGO", true, CultureInfo.InvariantCulture))
            {
                sql = $"select id, user_code, customer_name, company_code, admdiv_code, admdiv_name,group_id,status from customer_center where user_code = '{_userCode}'";
            }
            else
            {
                sql = $"select id, user_code, customer_name, company_code, admdiv_code, admdiv_name,group_id, status from customer_center where customer_name = '{await encryptHelper.EncryptAsync(_userCode)}'";
            }
            if (SelectedSite != "zwy")
            {
                var responseHeaders = await loginService.Login("zwy");
                if (responseHeaders == null)
                {
                    Snackbar.Add("登录失败", Severity.Error);
                    return;   
                }
                _customers = await customerService.GetCustomers(sql, "zwy", responseHeaders);
            }
            else
            {
                _customers = await customerService.GetCustomers(sql, SelectedSite, ResponseHeaders);
            }

            if (_customers == null || _customers.Count == 0)
            {
                Snackbar.Add("未获取到单位信息", Severity.Error);
            }
            else
            {
                var localSql = $"select a.id, a.user_code, a.customer_name, a.company_code, a.admdiv_code, a.admdiv_name,b.fin_admdiv_code from customer_base a inner join customer_extra b on a.user_code=b.user_code where a.user_code='{_customers.FirstOrDefault()?.UserCode}'";
                if (SelectedSite != "zwy")
                {
                    ResponseHeaders = await loginService.Login(SelectedSite);
                }
                var localCustomers = await customerService.GetLocalCustomers(localSql, SelectedSite, ResponseHeaders, _customers.FirstOrDefault()?.GroupName);
                if (localCustomers != null && localCustomers.Count > 0)
                {
                    foreach (var customer in _customers)
                    {
                        var localCustomer = localCustomers.FirstOrDefault(c => c.UserCode == customer.UserCode);
                        if (localCustomer != null)
                        {
                            customer.FinAdmdivCode = localCustomer.FinAdmdivCode;
                        }
                    }
                }
                _userCodeStr = _customers.FirstOrDefault()?.UserCode;
                await OnGetCustomer.InvokeAsync(_customers.FirstOrDefault());
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"发生异常: {ex.Message}");
            await dialogService.ShowAsync<ErrorDialog>("Error", new DialogParameters() { { "Content", ex.Message } });
        }
        finally
        {
            _processing = false;
        }
    }

}
